const CHUNK_SIZE = 1024 * 1024 * 3; // 3M
const THREAD_COUNT = navigator.hardwareConcurrency || 6; // 定义线程数量
export function curFile(file: any) {
  return new Promise((resolve) => {
    const result: any = []; // 存储切片结果的数组
    const chunkCount = Math.ceil(file.size / CHUNK_SIZE);  // 计算切片数量 向上取整
    const workerChunkCount = Math.ceil(chunkCount / THREAD_COUNT); // 计算每个线程计算切片数
    let finishCount = 0;

    for (let i = 0; i < THREAD_COUNT; i++) {
      const worker = new Worker(new URL("./worker.tsx", import.meta.url), {
        type: "module",
      });
      const startIndex = i * workerChunkCount;
      let endIndex = startIndex + workerChunkCount;
      if (endIndex > chunkCount) {
        endIndex = chunkCount;
      }
      worker.postMessage({
        file,
        CHUNK_SIZE,
        startIndex,
        endIndex,
      });
      worker.onmessage = (e: any) => {
        for (let i = startIndex; i < endIndex; i++) {
          result[i] = e.data[i - startIndex];
        }
        worker.terminate();
        finishCount++;
        if (finishCount === THREAD_COUNT) {
          resolve(result);
        }
      };
    }

    return result;
  });
}
